package com.supreme.nettyapp.generalserver.mqttserver.service;

import com.supreme.nettyapp.generalserver.mqttserver.handler.MqttServerInitializer;
import com.supreme.nettyapp.generalserver.mqttserver.props.MqttServerProps;
import com.supreme.nettyapp.generalserver.service.NettyServerService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class MqttServerService implements NettyServerService {

    @Resource
    private MqttServerProps mqttServerProps;

    @Async(value = "nettyTask")
    @Override
    public void startNettyServer() {
        Integer port = mqttServerProps.getPort();
        System.out.println("mqttServerStarter port = " + port);

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(MqttServerInitializer.INSTANCE);

            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    @Override
    public void destroyNettyServer() {

    }
}
